﻿using Kevin.Comm.Logger;
using Kevin.Comm.Utility;
using Kevin.Shop.Business.Core.Components.Cookie;
using Kevin.Shop.Business.Core.Components.Responser;
using Kevin.Shop.Business.Core.Member;
using Kevin.Shop.Business.Service.Entity.Helper;
using Kevin.Shop.Integration.ExpansionPlugin.OAuth;
using Kevin.Shop.Integration.ExpansionPlugin.OAuth.Entity;
using Kevin.Shop.Integration.ExpansionPlugin.OAuth.ForQQ;
using Kevin.Shop.Integration.ExpansionPlugin.OAuth.ForSina;
using RiderShop.Mobile.Common.Component;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Security;

namespace RiderShop.Mobile.Modle.Customer
{
    public class OAuthModel
    {

        static string callbackUrl = System.Configuration.ConfigurationManager.AppSettings["OAuthCallbackUrl"];
        public static String CreateConnectFactory(int type)
        {
            string authorize_url = string.Empty;
            Connect connect = null;
            String state = getGuid;
            OAuthSite site = (OAuthSite)type;
            switch (site)
            {
                case OAuthSite.Weibo:
                    connect = new WeiBo(site, callbackUrl);
                    authorize_url = connect.GetAuthorizeURL(ResponseType.Code, getGuid);
                    break;
                case OAuthSite.Tentent:
                    connect = new Kevin.Shop.Integration.ExpansionPlugin.OAuth.ForQQ.Tencent(site, callbackUrl);
                    authorize_url = connect.GetAuthorizeURL(ResponseType.Code, getGuid);
                    break;
            }
            return authorize_url;
        }


        private static String getGuid
        {
            get
            {
                String guide = Guid.NewGuid().ToString();
                //建议最好加密，我这里使用的是md5,你们自行修改。
                //guide = CMS.Common.SecurityObject.PassEncrypt(guide, 1);
                KevinCache.Insert("ConnectGuid", guide);
                return guide;
            }
        }

        public bool Verify(int site, string code)
        {
            var siteType = (OAuthSite)site;
            AccessToken tokenInfo = CreateConnect.CreateConnectAccessToken(siteType, code, callbackUrl);
            if (tokenInfo != null)
            {
                UserInfo info = null;
                switch (siteType)
                {
                    case OAuthSite.Tentent:
                        info = getDelegate(tokenInfo, getTencent);
                        break;
                    case OAuthSite.Weibo:
                        info = getDelegate(tokenInfo, getWeiBo);
                        break;
                    case OAuthSite.ZhifuBao:
                        break;
                }
                if (info != null)
                {
                    Tracer.TraceLog("4-OAutoCallbackEnt:" + Serializer.ConvertObjectToJson(info), "OAutoCallbackURL", "OAutoCallbackURL", false);
                    var existsUser = RestfulHelper.Query<UserBasicInfo>(SiteUrl.FormatUrl("Common_GetUserInfoByThirdId", info.siteUserName)); ;
                    if (existsUser.Count <= 0 || existsUser[0].UserId <= 0)
                    {
                        #region new userInfo
                        var userInfo = new UserBasicInfo();
                        userInfo.EnableEmail = false;
                        userInfo.RealName = info.screen_name;
                        userInfo.UserName = info.siteUserName;
                        userInfo.ThirdUserId = info.siteUserName;
                        userInfo.HeadImgUrl = info.profile_image_url;
                        userInfo.Address = info.location;
                        switch (info.uType)
                        {
                            case OAuthSite.Tentent:
                                userInfo.Email = info.siteUserName + "@qq.com";
                                break;
                            case OAuthSite.Weibo:
                                userInfo.Email = info.siteUserName + "@sina.com";
                                break;
                            case OAuthSite.ZhifuBao:
                                userInfo.Email = info.siteUserName + "@taobao.com";
                                break;
                        }
                        userInfo.Password = info.openId;
                        #endregion
                        //Tracer.TraceLog("5.O CreateUser:" + Serializer.ConvertObjectToJson(userInfo), "OAutoCallbackURL", "OAutoCallbackURL", true);
                        var response = RestfulHelper.Update(SiteUrl.FormatUrl("Common_CreateOrUpdateByWebSite"), userInfo);
                        Tracer.TraceLog("5.O AutoCallbackEntCreateUser:" + Serializer.ConvertObjectToJson(response), "OAutoCallbackURL", "OAutoCallbackURL", true);

                        if (response.Status)
                        {
                            var userList = RestfulHelper.Query<UserBasicInfo>(SiteUrl.FormatUrl("Common_GetUserInfoByThirdId", info.siteUserName));
                            if (userList.Count > 0 || userList[0].UserId > 0)
                            {
                                //Login in
                                var userName = userList[0].UserName;
                                Login(userName);

                                return true;
                            }
                            else
                            {
                                return false;
                            }
                        }
                    }
                    else
                    {
                        Login(existsUser[0].UserName);
                        return true;
                    }
                }
            }
            else
            {
                Tracer.TraceLog("2-OAutoCallback获取token异常," + siteType.ToString(), "OAutoCallbackURL", "OAutoCallbackURL", false);
                return false;
            }

            return true;
        }

        private static void Login(string userName)
        {
            Tracer.TraceLog("2-OAutoCallback登录：," + userName, "OAutoCallbackURL", "OAutoCallbackURL", false);
            HttpCookie authCookie = FormsAuthentication.GetAuthCookie(userName, true);
            KevinCookieManager.Set(authCookie.Name, authCookie.Value, 10000);
            WebClientContext.Current.GetCurrentUser();
            FormsAuthentication.RedirectFromLoginPage(userName, true);
        }



        #region Common_GetUserInfoByThirdId

        private delegate UserInfo myDelegateUserInfo(AccessToken tokenInfo);

        private UserInfo getDelegate(AccessToken token, myDelegateUserInfo myDelegate)
        {
            return myDelegate(token);
        }

        private UserInfo getWeiBo(AccessToken tokenInfo)
        {
            UserInfo info = null;
            WeiboParaeter[] parameter = new WeiboParaeter[]
                                            {
                                                new WeiboParaeter {Name = "uid", Value = tokenInfo.uid},
                                                new WeiboParaeter {Name = "source", Value = CreateConnect.GetAppk},
                                                new WeiboParaeter
                                                    {Name = "access_token", Value = tokenInfo.access_token}
                                            };
            String result = CreateConnect.
                GetCommand("https://api.weibo.com/2/users/show.json", parameter);
            if (!String.IsNullOrEmpty(result))
            {
                Tracer.TraceLog("3-OAutoCallbackEntWeiBo:" + result, "OAutoCallbackURL", "OAutoCallbackURL", false);
                info = Serializer.ConvertJsonToObject<UserInfo>(result);
                if (info != null && !string.IsNullOrEmpty(info.openId))
                {
                    info.gender = info.gender == "m" ? "男" : "女";
                    info.uType = OAuthSite.Weibo;
                }
            }
            return info;
        }

        private UserInfo getTencent(AccessToken tokenInfo)
        {
            UserInfo info = null;
            WeiboParaeter[] parameter = new WeiboParaeter[]
                                            {
                                                new WeiboParaeter
                                                    {Name = "oauth_consumer_key", Value = CreateConnect.GetAppk},
                                                new WeiboParaeter
                                                    {Name = "access_token", Value = tokenInfo.access_token},
                                                new WeiboParaeter {Name = "openid", Value = tokenInfo.openid}
                                            };
            String result = CreateConnect.GetCommand("https://graph.qq.com/user/get_user_info", parameter);
            Tracer.TraceLog("3-OAutoCallbackEntTencent:" + result, "OAutoCallbackURL", "OAutoCallbackURL", false);
            if (!String.IsNullOrEmpty(result))
            {
                TentenctInfo tentectInfo = Serializer.ConvertJsonToObject<TentenctInfo>(result);
                if (tentectInfo != null && !string.IsNullOrEmpty(tokenInfo.openid))
                {
                    info = new UserInfo
                    {
                        gender = tentectInfo.gender,
                        openId = tokenInfo.openid,
                        screen_name = tentectInfo.nickname,
                        location = String.Empty,
                        profile_image_url = tentectInfo.figureurl_qq_1,
                        uType = OAuthSite.Tentent
                    };
                }
            }
            return info;
        }

        #endregion
    }
}
